package net.sourceforge.stripes.authentication;

import org.apache.commons.codec.binary.Base64;

import javax.servlet.http.HttpServletRequest;

public class BasicAuthenticationChecker extends AbstractAuthenticationChecker
{
    public AuthenticatedUserInfo check(AuthenticationService authenticationService, HttpServletRequest request, String credentials) throws Exception
    {
        AuthenticatedUserInfo result = null;

        if (credentials.startsWith("Basic ") || credentials.startsWith("basic ")) {
            credentials = credentials.substring(credentials.indexOf(' ') + 1);
            credentials = new String(Base64.decodeBase64(credentials.getBytes()), "ISO-8859-1");
            int i = credentials.indexOf(':');
            if (i != -1) {
                String username = credentials.substring(0, i);
                String password = credentials.substring(i + 1);

                AuthenticatedUserInfo authenticatedUserInfo = authenticationService.getAuthenticatedUserInfo(username);
                if (authenticatedUserInfo != null && password.compareTo(authenticatedUserInfo.getHashedPassword()) == 0) {
                    result = authenticatedUserInfo;
                }
            }
        }

        return result;
    }
}
